<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
          <div class="search_wrap">
            <el-form :inline="true" :model="filters" ref="searchForm" v-if="userRole==1">
              <el-form-item prop="businessId">
                <el-select v-model="filters.businessId" :clearable="true" placeholder="商户名称" clearable filterable>
                  <el-option v-for="item in businessList" :value="item.id" :label="item.name" :key="item.id">

                  </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item prop="busienssId">
                <el-input v-model="filters.busienssId" :clearable="true" placeholder="商户"></el-input>
              </el-form-item>
              <el-form-item prop="levels">
                <el-select v-model="filters.levels" clearable placeholder="选择等级">
                  <el-option v-for="item in levelsList" :value="item.value" :label="item.label" :key="item.value">

                  </el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item>
                <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
                <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <!-- <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button> -->
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <tree-table id="scrollDiv" :customRow="handleClickRow" :key='tableKey' :columns="columns" :data="treeTableList" :eval-func="func"
        :eval-args="args" :expand-all="expandAll" :height="maxHeight + 40" border>
        <el-table-column width="400px" align="center" label="所属商户">
          <template slot-scope="scope">
            <span>{{ scope.row.businessName }}</span>
          </template>
        </el-table-column>
        <el-table-column width="240px" align="center" label="等级">
          <template slot-scope="scope">
            <span class="">{{ formatLevels(scope.row.levels) }}</span>
          </template>
        </el-table-column>
        <el-table-column width="100px" align="center" label="状态">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="plain" :type="formatStates(scope.row.state)">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建人" prop="createUserName">

        </el-table-column>
        <el-table-column align="center" label="创建时间" prop="createDate">

        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="300px" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <div class="operate-box">
              <el-button v-has="permissionAdd" v-if="judgePermiss(scope.row, 1)" type="text" size="mini"
                icon="el-icon-document-add" @click="handleClickAdd(scope.row)">新增下级</el-button>

              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu>
                  <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)" v-if="judgePermiss(scope.row, 2)">
                      编辑
                  </el-dropdown-item>
                  <el-dropdown-item v-if="judgePermiss(scope.row, 3)" v-has="permissionBindManager" @click.native="handleBindManager(scope.row)">
                      绑定管理员
                  </el-dropdown-item>
                  <el-dropdown-item v-has="permissionCheck" @click.native="handleClickDetail(scope.row)">
                      查看
                  </el-dropdown-item>
                  <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)" v-if="judgePermiss(scope.row, 3)">
                     删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

              <!-- <el-button v-has="permissionUpStatus"
                           type="text" size="mini" icon="el-icon-check"
                           @click="handleClickEnable(scope.row)" v-if="scope.row.state === 0&&scope.row.power">启用</el-button>
                <el-button v-has="permissionUpStatus"
                           type="text" size="mini" icon="el-icon-close"
                           @click="handleClickDisable(scope.row)" v-if="scope.row.state === 1&&scope.row.power">禁用</el-button> -->

            </div>
          </template>
        </el-table-column>
      </tree-table>
    </el-row>
    <BindBsManager v-model="bindManagers.showBindManager" :departId="bindManagers.departId"></BindBsManager>
  </div>
</template>
<script>
import * as message from "@/constants/message";
import treeToArray from '@/utils/customEval';
import treeTable from '@/components/TreeTable';
import BusinessDepartApi from "@/api/business/depart"
import BindBsManager from "../../components/BindBsManager.vue";
import BusinessApi from "@/api/business/business";
export default {
  name: 'BusinessDepartManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      filters: {
        // menuName: "",
        // menuCode: ""
        businessId:"",
      },
      userRole: "",
      detailRole: "",
      tableKey: 0,
      total: null,
      func: treeToArray,
      args: [],
      list: {},
      treeTableList: [],
      //开始切割的位置
      starSize: 0,
      //结束位置
      endSize: 20,
      totalSize: [],
      // list2: undefined,
      expandAll: false,
      columns: [
        {
          text: '部门名称',
          value: 'departName',
          width: 220
        }
      ],
      levelsList: [
        { value: 1, label: "商户" },
        { value: 2, label: "部门" },
        { value: 3, label: "组" },
        { value: 4, label: "岗位" },
      ],
      businessList: [],
      maxHeight:500,
      tableList: [],
      permissionCheck: 'SYSTEM_MANAGER_BUSINESS_DEPART_LIST_SEE',
      permissionAdd: 'SYSTEM_MANAGER_BUSINESS_DEPART_LIST_ADD',
      permissionEdit: 'SYSTEM_MANAGER_BUSINESS_DEPART_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_BUSINESS_DEPART_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_BUSINESS_DEPART_LIST_DELETE',
      permissionBindManager:"SYSTEM_MANAGER_BUSINESS_DEPART_LIST_BIND_MANAGER",
      bindManagers: {
        showBindManager: false,
        departId: "",
      },
    }
  },
  components: {
    treeTable,
    BindBsManager
  },
  mounted() {
    this.init();
    //window.addEventListener("keydown", this.keyDown);
  },
  activated() {
    this.listTable();
  },
  destroyed() {
    //window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    //懒加载1-节流函数
    throttle(fn, delay) {
      let valid = true;
      return function () {
        if (!valid) {
          //休息时间 暂不执行
          return false;
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false;
        setTimeout(() => {
          fn();
          valid = true;
        }, delay);
      };
    },
    //懒加载2-触发方法
    triggerScroll() {
      document
        .querySelector("#scrollDiv .el-table__body-wrapper")
        .addEventListener("scroll", this.throttle(this.handleScroll, 500));
    },
    //懒加载3-主体方法
    handleScroll() {
      let scrollTop = document.querySelector("#scrollDiv .el-table__body-wrapper").scrollTop;
      let scrollHeight = document.querySelector("#scrollDiv .el-table__body-wrapper").scrollHeight;
      let clientHeight = document.querySelector("#scrollDiv .el-table__body-wrapper").clientHeight;
      if (this.totalSize.length == this.treeTableList.length) {
        //表示已到底部
        return;
      }
      if (scrollHeight - clientHeight - scrollTop < 30) {
        //监听滚动条到底部
        this.starSize = this.starSize + 20;
        this.endSize = this.endSize + 20;
        let arrOne = this.treeTableList;
        let arrTwo = this.totalSize.slice(this.starSize, this.endSize);
        this.treeTableList = arrOne.concat(arrTwo);
      }
    },
    init() {
      this.detailRole = this.$store.getters.detailRole
      this.userRole = this.$store.getters.userRole
      this.getBusinessList()
      this.getTableHeight();
      this.listTable();
      this.triggerScroll()
    },
    /*keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },*/
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        }
      })
    },
    // 获取商户列表
    getBusinessList() {
        BusinessApi.listIdNameVo().then(res => {
            this.businessList = res.data
        })
    },
    handleBindManager(row){
      this.bindManagers.showBindManager = true
      this.bindManagers.departId = row.departId
    },
    judgePermiss(row, type) {
      switch (type) {
        case 1:
          if (this.userRole == 3) {
            return row.power && row.levels != 3 && this.detailRole <= row.levels
          } else {
            return row.power && row.levels != 3
          }
        case 2:
          if (this.userRole == 3) {
            return row.power && this.detailRole < row.levels||row.power&&!this.detailRole
          } else {
            return row.power
          }

        case 3:
          if (this.userRole == 3) {
            return row.power && this.detailRole < row.levels||row.power&&!this.detailRole
          } else {
            return row.power && row.levels
          }

      }

    },
    listTable() {
      let _this = this
      _this.starSize = 0
      _this.endSize = 20
      let data = {
        businessId: _this.filters.businessId,
      };
      _this.$emit('show-loading', true);
      BusinessDepartApi.listBusinessDeparts(data)
        .then(res => {
          _this.totalSize = res.data;
          if (_this.totalSize.length > 20) {
            _this.treeTableList = _this.totalSize.slice(
              _this.starSize,
              _this.endSize
            );

          } else {
            _this.treeTableList = _this.totalSize;
          }
          _this.$emit('show-loading', false);
        }).catch(err => {
          _this.listLoading = false
        });
    },
    handleClickAdd(row) {
      this.$router.push({
        path: "/business/businessDepartAdd",
        query: {
          parentId: row.departId,
          parentName: row.departName,
        }
      });
    },
    handleClickEditor(row) {
      const query = {
        id: row.departId,
      }
      if (row.parent) {
        query.parentId = row.parent.departId,
          query.parentName = row.parent.departName
      }
      this.$router.push({
        path: "/business/businessDepartEdit",
        query,
      });
    },
    handleClickDetail(row) {
      this.$router.push({ path: "/business/businessDepartDetail", query: { id: row.departId } })
    },
    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {})
        .then(() => {
          let data = {
            id: row.departId,
            state: -1
          };
          BusinessDepartApi.deleteBusinessDepart(data)
            .then(res => {
              if (data.state != -1) {
                row.state = data.state;
              } else {
                this.listTable();
              }
              this.$Utils.notifySuccess()
            })
        })
    },
    formatLevels(cellValue) {
      if (cellValue === 0) {
        return "商户"
      } else if (cellValue === 1) {
        return "部门"
      } else if (cellValue === 2) {
        return "组"
      } else if (cellValue === 3) {
        return "岗位"
      }
    },
    formatState(cellValue) {
      if (cellValue === -1) {
        return "删除"
      } else if (cellValue === 0) {
        return "禁用"
      } else if (cellValue === 1) {
        return "启用"
      }
    },
    formatStates(cellValue) {
      if (cellValue === -1) {
        return "danger"
      } else if (cellValue === 0) {
        return "warning"
      } else if (cellValue === 1) {
        return "success"
      }
    },
    onSearch() {
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch()
    },

    handleClickRow(record, index) {
      return {
        on: {
          click: () => {
            console.log(record, index)
            console.log('点击行内容record' + record)
            console.log('序号索引index' + index)
          }
        }
      }
    }

  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
<style lang="scss">
@import "@/assets/css/views/content.scss";
</style>
